package com.ssy.filter;


import cn.hutool.core.util.StrUtil;
import com.ssy.common.CodeMsg;
import com.ssy.common.Result;
import com.ssy.util.RespUtil;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * LoginFilter
 *
 * @author ssy
 * @date 2020/11/20
 **/
@WebFilter(urlPatterns = {"*.jsp", "*.do"})
public class LoginFilter implements Filter {


    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse resp = (HttpServletResponse) response;
        boolean isAjaxRequest = false;
        //判断请求是否为AJAX请求
        String ajaxHeader = req.getHeader("x-requested-with");
        if (StrUtil.equals(ajaxHeader, "XMLHttpRequest")) {
            isAjaxRequest = true;
        }
        Object user = req.getSession().getAttribute("user");
        if (user != null) {
            chain.doFilter(request, response);
        } else {
            String requestURI = req.getRequestURI();
            //登录页面放过
            if (requestURI.endsWith("index.jsp")) {
                chain.doFilter(request, response);
                return;
            }
            //验证码请求放过
            if (requestURI.endsWith("CheckCode.do")) {
                chain.doFilter(request, response);
                return;
            }
            //登录请求放过
            String type = req.getParameter("type");
            if (requestURI.endsWith("user.do")) {
                if ("login".equals(type)) {
                    chain.doFilter(request, response);
                    return;
                }
            }

            //session 登录失效
            if (user == null && isAjaxRequest) {
                RespUtil.write(resp, new Result(CodeMsg.USER_SESSION_INVALI_ERROR));
                return;
            }

            resp.sendRedirect("index.jsp");
        }
    }

    @Override
    public void destroy() {

    }
}
